//
//  HomePageViewController.m
//  HuiKaoClient
//
//  Created by 龚 杰 on 13-2-20.
//  Copyright (c) 2013年 龚 杰. All rights reserved.
//

#import "HomePageViewController.h"
#import "MainTabBarController.h"
#import "ASIHTTPRequest.h"
#import "CJSONDeserializer.h"
#import <QuartzCore/QuartzCore.h>
#import "asyncimageview.h"
#import "WebNewsViewController.h"
#import "KaoNewsViewController.h"
#import "MeterialListViewController.h"
#import "AppDelegate.h"
#import "BookShopViewController.h"
#import "PeiXunViewController.h"
#import "GOWebViewController.h"
#import "pblasyncimageview.h"
@interface HomePageViewController ()

@end

@implementation HomePageViewController

- (id)init
{
    if (self = [super init]) {
        // Custom initialization
    }
    return self;
}

-(void) dealloc
{
    [_ProView release];
    [_PageDataArr release];
    [_ADSScrollView release];
    [m_titleBttBarItem release];
    [super dealloc];
}

-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([m_titleBttBarItem superview] == nil) {
        [self.navigationController.navigationBar addSubview:m_titleBttBarItem];
    }
    MainTabBarController* tMainTabController = (MainTabBarController*)self.navigationController.tabBarController;
    tMainTabController.mainselectedIndex =  tMainTabController.selectedIndex;
}
-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if ([m_titleBttBarItem superview]) {
        [m_titleBttBarItem removeFromSuperview];
    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    if([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        if ([self.navigationController.navigationBar viewWithTag:0x300] == nil) {
            UIImageView* tImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"titleBar.png"]];
            tImgView.tag =0x300;
            tImgView.frame =CGRectMake(0, 0, 320, 44);
            [self.navigationController.navigationBar addSubview:tImgView];
            [tImgView release];
        }
    }
    m_titleBttBarItem = [[MainTabBarController setTitle:@"公务员考试网"] retain];

    
    //RequestTestURL
    _ADSScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 148)];
    _ADSScrollView.pagingEnabled =YES;
    _ADSScrollView.showsHorizontalScrollIndicator =NO;
    _ADSScrollView.showsVerticalScrollIndicator = NO;
    _ADSScrollView.delegate = self;
    [self.view addSubview:_ADSScrollView];
    
    CALayer* tRectLayer = [CALayer layer];
    tRectLayer.frame =CGRectMake(10, _ADSScrollView.frame.size.height+13, 300, 190);
    tRectLayer.borderWidth  =1;
    tRectLayer.borderColor = [UIColor colorWithCGColor:[UIColor grayColor].CGColor].CGColor;
    tRectLayer.cornerRadius =4.f;
    [self.view.layer addSublayer:tRectLayer];
    
    CALayer* tLineMidLayer = [CALayer layer];
    tLineMidLayer.frame =CGRectMake(10, tRectLayer.frame.origin.y+tRectLayer.frame.size.height/2, 300, 1);
    [tLineMidLayer setBackgroundColor:[UIColor lightGrayColor].CGColor];
    [self.view.layer addSublayer:tLineMidLayer];
    
    CALayer* tLineHLayer = [CALayer layer];
    tLineHLayer.frame =CGRectMake(160, tRectLayer.frame.origin.y, 1, tRectLayer.frame.size.height);
    [tLineHLayer setBackgroundColor:[UIColor lightGrayColor].CGColor];
    [self.view.layer addSublayer:tLineHLayer];
    
    NSMutableArray* tImgArr = [NSMutableArray arrayWithObjects:@"index_news.png",@"index_shop.png",@"index_firm.png",@"index_meterial.png", nil];
    
    NSMutableArray* tNameArr = [NSMutableArray arrayWithObjects:@"公考资讯",@"最新资讯全接触", @"图书商城",@"图书在线订购", @"培训机构",@"立刻报名培训", @"学习资料",@"学习资料下载", nil];
    for (int i=0; i<[tImgArr count]; i++) {
        NSString* tImgName =[tImgArr objectAtIndex:i];
        UIImage* tIconImg = [UIImage imageNamed:tImgName];
        UIImageView* tImgView0 = [[UIImageView alloc] initWithFrame:CGRectMake(18+(i%2)*152, tRectLayer.frame.origin.y+22+(i/2)*95, 48, 48)];
        [tImgView0 setImage:tIconImg];
        [self.view addSubview:tImgView0];
        [tImgView0 release];
        
        NSString* tTitleStr =[tNameArr objectAtIndex:i*2];
        NSString* tDesStr = [tNameArr objectAtIndex:i*2+1];
        
        UILabel* tTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(18+(i%2)*152+54, tRectLayer.frame.origin.y+22+(i/2)*95+6, 120, 20)];
        [tTitleLab setBackgroundColor:[UIColor clearColor]];
        [tTitleLab setText:tTitleStr];
        [tTitleLab setFont:[UIFont systemFontOfSize:18]];
        [self.view addSubview:tTitleLab];
        [tTitleLab release];
        
        UILabel* tDesLab = [[UILabel alloc] initWithFrame:CGRectMake(18+(i%2)*152+55, tRectLayer.frame.origin.y+22+(i/2)*95+28, 120, 20)];
        [tDesLab setBackgroundColor:[UIColor clearColor]];
        [tDesLab setText:tDesStr];
        [tDesLab setFont:[UIFont systemFontOfSize:10]];
        [tDesLab setTextColor:[UIColor grayColor]];
        [self.view addSubview:tDesLab];
        [tDesLab release];
        
        UIButton* tModeBtt = [UIButton buttonWithType:UIButtonTypeCustom];
        [tModeBtt addTarget:self action:@selector(modePressed:) forControlEvents:UIControlEventTouchUpInside];
        tModeBtt.frame =CGRectMake(10+(i%2)*150, tRectLayer.frame.origin.y+i/2*95, 150, 95);
        tModeBtt.tag =i;
        [self.view addSubview:tModeBtt];
    }

    
    [self addHudLoad];
    NSString* tURLStr = [NSString stringWithFormat:@"%@ac=getIndexInfo",RequestCurrentURL];
    ASIHTTPRequest* tRequestPage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:tURLStr]];
    [tRequestPage setDelegate:self];
    [tRequestPage setDidFailSelector:@selector(requestPageFail:)];
    [tRequestPage setDidFinishSelector:@selector(requestPageFinish:)];
    [tRequestPage startAsynchronous];
    
    [self requestCityData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//模式点击
-(void) modePressed:(UIButton*)f_sender
{
    int tTypeIndex = f_sender.tag;
    if (tTypeIndex == 0) {
        KaoNewsViewController* tKaoNewsVC = [[KaoNewsViewController alloc] init];
        tKaoNewsVC.hidesBottomBarWhenPushed =YES;
        tKaoNewsVC.navigationItem.hidesBackButton =YES;
        [self.navigationController pushViewController:tKaoNewsVC animated:YES];
        [tKaoNewsVC release];
    }else if(tTypeIndex == 1){
        BookShopViewController* tBSVC = [[BookShopViewController alloc] init];
        tBSVC.navigationItem.hidesBackButton =YES;
        tBSVC.hidesBottomBarWhenPushed =YES;
        [self.navigationController pushViewController:tBSVC animated:YES];
        [tBSVC release];
    }else if(tTypeIndex == 2){
        PeiXunViewController* tBSVC = [[PeiXunViewController alloc] init];
        tBSVC.navigationItem.hidesBackButton =YES;
        tBSVC.hidesBottomBarWhenPushed =YES;
        [self.navigationController pushViewController:tBSVC animated:YES];
        [tBSVC release];
    }else{
        MeterialListViewController* tMeterialVC = [[MeterialListViewController alloc] init];
        tMeterialVC.hidesBottomBarWhenPushed =YES;
        tMeterialVC.navigationItem.hidesBackButton =YES;
        [self.navigationController pushViewController:tMeterialVC animated:YES];
        [tMeterialVC release];
    }
}
//广告点击
-(void) scrollBttPressed:(UIButton*)f_sender
{
    int tTypeIndex = f_sender.tag;
    
    GOWebViewController* tWebNewsVC = [[GOWebViewController alloc] init];
    tWebNewsVC.WebURL =[[_PageDataArr objectAtIndex:tTypeIndex] objectForKey:@"url"];
    tWebNewsVC.hidesBottomBarWhenPushed =YES;
    tWebNewsVC.navigationItem.hidesBackButton =YES;
    [self.navigationController pushViewController:tWebNewsVC animated:YES];
    [tWebNewsVC release];

}

-(void) requestPageFail:(ASIHTTPRequest*)request
{
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"网络错误" detailText:@"" isCue:YES delayTime:2];
    [self hudWasHidden:nil];
}
-(void) requestPageFinish:(ASIHTTPRequest*)request
{
    NSError* tError;
    NSString* tReqStr = [request responseString];
    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            NSDictionary* tRealDataDic = [tDataDic objectForKey:@"data"];
            _PageDataArr =[tRealDataDic objectForKey:@"news"];
            [_PageDataArr retain];
            NSFileManager* tFileManager = [NSFileManager defaultManager];
            NSString* tTemp = NSTemporaryDirectory();
            NSString *pblName=[tTemp stringByAppendingPathComponent:@"bufftmp"];
            int tIndex =0;
            for (NSDictionary* tDic in _PageDataArr) {
                NSString* tImgLocalURL =[pblName stringByAppendingPathComponent:[NSString stringWithFormat:@"%d",tIndex]];
                if ([tFileManager fileExistsAtPath:tImgLocalURL]) {
                    UIImageView* tAdsImgView = [[UIImageView alloc] initWithFrame:CGRectMake(tIndex*320, 0, 320, _ADSScrollView.frame.size.height)];
                    [tAdsImgView setImage:[UIImage imageWithContentsOfFile:tImgLocalURL]];
                    [_ADSScrollView addSubview:tAdsImgView];
                    [tAdsImgView release];
                }
                
                PBLAsyncImageView* tImgView = [[PBLAsyncImageView alloc] initWithFrame:CGRectMake(tIndex*320, 0, 320, _ADSScrollView.frame.size.height)];
                tImgView.m_BoolSetImage =YES;
                tImgView._numStateRequested =need_Request;
                tImgView._imageRequestURL =[tDic objectForKey:@"image"];
                tImgView.m_FloderName = @"bufftmp";
                tImgView.m_PngName = [NSString stringWithFormat:@"%d",tIndex];
                [_ADSScrollView addSubview:tImgView];
                [tImgView customLoadImageFromURL];
                [tImgView release];
                
                UIButton* tCusBtt = [UIButton buttonWithType:UIButtonTypeCustom];
                tCusBtt.frame =CGRectMake(tIndex*320, 0, 320, _ADSScrollView.frame.size.height);
                tCusBtt.tag =tIndex;
                [tCusBtt addTarget:self action:@selector(scrollBttPressed:) forControlEvents:UIControlEventTouchUpInside];
                [_ADSScrollView addSubview:tCusBtt];
                tIndex++;
            }
            [_ADSScrollView setContentSize:CGSizeMake(320*[_PageDataArr count], _ADSScrollView.frame.size.height)];
            
            _ProModeW = 320/tIndex;
            _ProView = [[UIView alloc] initWithFrame:CGRectMake(0, _ADSScrollView.frame.size.height-7, 320, 6)];
            [self.view addSubview:_ProView];
            for (int i=0; i<tIndex; i++) {
                UIView* tGrayView = [[UIView alloc] initWithFrame:CGRectMake(i*_ProModeW, 0, _ProModeW-1, 6)];
                [tGrayView setBackgroundColor:[UIColor lightGrayColor]];
                tGrayView.alpha =0.5f;
                [_ProView addSubview:tGrayView];
                [tGrayView release];
            }
            UIView* tRedView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _ProModeW-1, 6)];
            tRedView.tag =10;
            [tRedView setBackgroundColor:[UIColor redColor]];
            [_ProView addSubview:tRedView];
            [tRedView release];
        }else{
            AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:YES delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:YES delayTime:2];
            }
            
        }
    }
    [self hudWasHidden:nil];
}

//城市需求请求
-(void) requestCityData
{
    ASIHTTPRequest* tRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@ac=getProvinceList",RequestCurrentURL]]];
    [tRequest setDelegate:self];
    [tRequest setDidFailSelector:@selector(requestCityFailed:)];
    [tRequest setDidFinishSelector:@selector(requestCityFinish:)];
    [tRequest startAsynchronous];
}

-(void) requestCityFailed:(ASIHTTPRequest*)request
{
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"网络错误" detailText:@"" isCue:YES delayTime:2];
    [self hudWasHidden:nil];
}
-(void) requestCityFinish:(ASIHTTPRequest*)request
{
    NSError* tError;
    NSString* tReqStr = [request responseString];
    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            NSDictionary* tRealDataDic = [tDataDic objectForKey:@"data"];
            NSDictionary* tListDic = [tRealDataDic objectForKey:@"list"];
            NSString* tNumStr = nil;
            for (int i=1000; i<2000; i++) {
                tNumStr = [NSString stringWithFormat:@"%d",i];
                NSDictionary* tCityDic = [tListDic objectForKey:tNumStr];
                if (tCityDic != nil) {
                    [tAppDel.m_CityDataArr addObject:tCityDic];
                }else{
                    break;
                }
            }
        }else{
            AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:YES delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:YES delayTime:2];
            }
        }
    }
    [self hudWasHidden:nil];
}

#pragma mark -
#pragma mark UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    UIView* tRedView = [_ProView viewWithTag:10];
    CGRect aFrame =tRedView.frame;
    aFrame.origin.x = scrollView.contentOffset.x/320*_ProModeW;
    tRedView.frame =aFrame;
}
#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
	[_MBHUD removeFromSuperview];
    _MBHUD.delegate = nil;
	[_MBHUD release];
	_MBHUD=nil;
}

-(void) addHudLoad{
	if (_MBHUD == nil) {
		_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
		[tAppDel.window addSubview:_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		_MBHUD.delegate = self;
		_MBHUD.labelText = @"请求数据中...";
		[_MBHUD show:YES];
	}
}

@end
